package com.hooper.iot.resource.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.hooper.iot.resource.constant.UnifyDeviceTypeNum;
import com.hooper.iot.resource.entity.DeviceFeignRes;
import com.hooper.iot.resource.feign.UnifyDeviceFeign;
import com.hooper.iot.resource.service.UnifyDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class UnifyDeviceServiceImpl implements UnifyDeviceService {

    private static final String UNIFY_QUERY_CONSTANTS = "id,gbid,name,status,deviceType,deviceName,groupId,address,businessCode,latitude,longitude,deviceAttr";

    @Resource
    private UnifyDeviceFeign unifyDeviceFeign;

    @Override
    public List<DeviceFeignRes.DeviceData> query(UnifyDeviceTypeNum deviceTypeNum) {
        try {
            String resultStr = this.unifyDeviceFeign.findDeviceByType(deviceTypeNum.getUnifyType(), false, UNIFY_QUERY_CONSTANTS);
            log.info("统一设备回应信息：{}", resultStr);
            DeviceFeignRes unifyDeviceResponse = JSON.parseObject(resultStr, DeviceFeignRes.class);
            if (Objects.nonNull(unifyDeviceResponse) && Objects.nonNull(unifyDeviceResponse.getResult()) && CollectionUtil.isNotEmpty(unifyDeviceResponse.getResult().getData())) {
                return unifyDeviceResponse.getResult().getData();
            }
        } catch (Exception e) {
            log.error("query unify-device error :{}", e.getMessage());
        }
        return null;
    }

    @Override
    public List<DeviceFeignRes.DeviceData> query(UnifyDeviceTypeNum deviceTypeNum, String accessId) {
        try {
            String resultStr = this.unifyDeviceFeign.findDeviceByTypeAndAccessId(accessId, deviceTypeNum.getUnifyType(), false, UNIFY_QUERY_CONSTANTS);
            log.info("统一设备回应信息：{}", resultStr);
            DeviceFeignRes unifyDeviceResponse = JSON.parseObject(resultStr, DeviceFeignRes.class);
            if (Objects.nonNull(unifyDeviceResponse) && Objects.nonNull(unifyDeviceResponse.getResult()) && CollectionUtil.isNotEmpty(unifyDeviceResponse.getResult().getData())) {
                return unifyDeviceResponse.getResult().getData();
            }
        } catch (Exception e) {
            log.error("query unify-device error :{}", e.getMessage());
        }
        return null;
    }
}
